<template>
  <div class="card w-100% h-100% flex justify-between">
    <el-card class="w-25% h-95%" shadow="never">
      <el-card class="h-40vh" shadow="never">
        <template #header>
          <div class="flex justify-between">
            <span>文件分类 </span>
            <el-switch v-auth="'recycle'" v-model="searchForm.deleted" inline-prompt
              style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66" :active-icon="ImBin"
              :inactive-icon="ImEye" @change="modelChange()" />
          </div>
        </template>
        <div class="h-30vh" style="overflow: auto;">
          <div class="grid grid-cols-4 gap-y-5">
            <div @click="typeClick(item)" class="flex flex-col items-center p-2 iconHover"
              :class="{ 'isactive': searchForm.fileType === item.type }" v-for="(item, index) in fileGroupList">
              <component :key="index" :is="item.icon" :color="item.color" :size="32"></component>
              <span style="font-size: 12px;">{{ item.name }}</span>
            </div>
          </div>
        </div>

        <div>
        </div>
      </el-card>
      <el-card class="h-30vh mt-2" shadow="never" v-auth="'add'" v-show="searchForm.deleted === false">
        <template #header>
          文件上传
        </template>
        <el-upload ref="upload" drag :action="uploadUrl" :on-success="handleSuccess" :on-error="handleError"
          :before-upload="beforeUpload" :headers="headers">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-card>
    </el-card>
    <el-card class="w-73% h-95%" shadow="never">
      <el-row>
        <el-col :span="24">
          <el-form v-auth="'search'" :inline="true" :model="searchForm">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="searchForm.fileName" placeholder="请输入文件名称" clearable
                @keyup.enter="search()"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-auth="'search'" @click="search()">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" v-auth="'clear'" v-if="searchForm.deleted === true"
                @click="handelDeleteAllFile()">清空回收站</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row class="h-60vh">
        <el-col :span="24">
          <el-table border :data="tableData" style="width: 100%">
            <el-table-column width="80" v-if="searchForm.fileType == '0'" label="缩略图" prop="previewUrl">
              <template #default="scope">
                <div class="flex justify-center">
                  <el-image style="width: 40px; height: 40px" :src="scope.row.previewUrl" :zoom-rate="1.2"
                    :max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.previewUrl]" show-progress
                    :initial-index="4" :preview-teleported="true" fit="cover" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="文件名称" prop="fileName" />
            <el-table-column label="文件大小" prop="fileSize">
              <template #default="{ row }">
                {{ formatFileSize(row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column label="上传时间" prop="createTime">
            </el-table-column>
            <el-table-column width="60" label="操作" v-auth="['download','url','recover','delete','deleteFile']">
              <template #default="scope">
                <el-dropdown trigger="click">
                  <div class="avatar">
                    <el-button type="primary" :icon="Tools" circle />
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <div v-auth="'download'">
                        <el-dropdown-item v-if="searchForm.deleted != true"
                          @click="handleDownload(scope.row.downloadUrl)">
                          <el-icon>
                            <Download />
                          </el-icon>下载
                        </el-dropdown-item>
                      </div>
                      <div v-auth="'url'">
                        <el-dropdown-item v-if="searchForm.deleted != true" @click="copyUrl(scope.row.previewUrl)">
                          <el-icon>
                            <CopyDocument />
                          </el-icon>复制url链接
                        </el-dropdown-item>
                      </div>
                      <div v-auth="'recover'">
                        <el-dropdown-item v-if="searchForm.deleted === true" @click="handleRecover(scope.row.id)">
                          <el-icon>
                            <ImReply />
                          </el-icon>恢复
                        </el-dropdown-item>
                      </div>
                      <div v-auth="'delete'">
                        <el-dropdown-item v-if="searchForm.deleted != true" divided style="color: #f56c6c"
                          @click="handleDelete(scope.row.id)">
                          <el-icon>
                            <Delete />
                          </el-icon>删除
                        </el-dropdown-item>
                      </div>
                      <div v-auth="'deleteFile'">
                        <el-dropdown-item  v-if="searchForm.deleted === true"
                          style="color: #f56c6c" @click="handleDeleteFile(scope.row.id)">
                          <el-icon>
                            <Delete />
                          </el-icon>彻底删除
                        </el-dropdown-item>
                      </div>

                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="justify-end">
        <el-pagination v-model:current-page="searchForm.current" v-model:page-size="searchForm.size"
          layout="total,sizes,prev, pager, next,jumper" :page-sizes="[10, 50, 100, 200, 500]" :total="total"
          @size-change="handleSizeChange" :background="true" @current-change="handleCurrentChange" />
      </el-row>
    </el-card>

  </div>
</template>
<script setup>
defineOptions({
  name: 'sysFile',
});
import { ref, onMounted } from "vue";
import { getSysFileList, deleteSysFile, recover, deleteFile, deleteAllFile } from "@/api/modules/sysFile";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import copy from "@/directives/modules/copy";
import {
  Tools
} from '@element-plus/icons-vue'
import { ImBin, ImEye } from "vue-icons-plus/im";
const searchForm = ref({
  fileName: "",
  fileType: "",
  fileSuffix: "",
  deleted: false,
  size: 10,
  current: 1
});

const fileList = ref([]);
const upload = ref();
const handleChange = file => {
  fileList.value = [];
};
const uploadUrl = "/admin/file/upload";

const userStore = useUserStore();
const headers = ref({
  Authorization: `Bearer ${userStore.token}`
});
const handleSuccess = res => {
  ElMessage.success("上传成功！");
  upload.value.clearFiles();
  search();
};
const handleError = res => {
  ElMessage.error("上传失败！");
  upload.value.clearFiles();
};

const beforeUpload = file => {
  const isLt10G = file.size / 1024 / 1024 < 10000;
  if (!isLt10G) {
    ElMessage.error("上传文件大小不能超过 10G!");
  }
  return isLt10G;
};
const search = () => {
  getSysFileList(searchForm.value).then(res => {
    tableData.value = res.data.others;
    total.value = res.data.total;
  });
};
const modelChange = () => {
  searchForm.value.fileType = ""
  search();
};
const fileGroupList = ref([
  {
    type: "0",
    name: "图片",
    icon: "ImImages",
    color: "#409EFF"
  },
  {
    type: "1",
    name: "视频",
    icon: "ImFileVideo",
    color: "#67C23A"
  },
  {
    type: "2",
    name: "DOC",
    icon: "ImFileWord",
    color: "#1d70f5"
  },
  {
    type: "3",
    name: "EXCEL",
    icon: "ImFileExcel",
    color: "#069e61"
  },
  {
    type: "4",
    name: "PPT",
    icon: "ImFileOpenoffice",
    color: "#f5670f"
  },
  {
    type: "5",
    name: "PDF",
    icon: "ImFilePdf",
    color: "#eb2f3b"
  },
  {
    type: "6",
    name: "音频",
    icon: "ImFileMusic",
    color: "#ff0000"
  },
  {
    type: "7",
    name: "txt",
    icon: "ImFileText2",
    color: "#fcc800"
  },
  {
    type: "9",
    name: "其他",
    icon: "ImFileEmpty",
    color: "#909399"
  },
  {
    type: "",
    name: "所有",
    icon: "ImStack",
    color: "#f56c6c"
  }
]);
const tableData = ref([]);
const total = ref(0);
// 文件大小格式化方法
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}
const handleSizeChange = val => {
  searchForm.value.size = val;
  search();
};
const handleCurrentChange = val => {
  searchForm.value.current = val;
  search();
};
const editSysFileRef = ref(null);
const handleAdd = () => {
  editSysFileRef.value.openDialog();
};
const handleEdit = row => {
  editSysFileRef.value.openDialog(row.id);
};
const handleDelete = id => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteSysFile(id).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功！");
        search();
      }
    });
  });
};

const handleDeleteFile = id => {
  ElMessageBox.confirm("确定要彻底删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteFile(id).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功！");
        search();
      }
    });
  });
};
const typeClick = item => {
  debugger
  if (searchForm.value.fileType != item.type) {
    searchForm.value.fileType = item.type;
  } else {
    searchForm.value.fileType = ""
  }
  search();
};

const handleDownload = url => {
  const a = document.createElement('a');
  a.href = url;
  a.download = url.split('/').pop(); // 可选：设置下载文件名
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

const handleRecover = id => {
  ElMessageBox.confirm("确定要恢复吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    recover(id).then(res => {
      if (res.code === 200) {
        ElMessage.success("恢复成功！");
        search();
      }
    });
  });
};

const handelDeleteAllFile = id => {
  ElMessageBox.confirm("确定要彻底清空回收站的文件吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error"
  }).then(() => {
    deleteAllFile().then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功！");
        search();
      }
    });
  });
}
const copyUrl = async url => {
  try {
    await navigator.clipboard.writeText(url);
    ElMessage.success("复制url链接成功！");
  } catch (err) {
    console.error('无法复制到剪贴板: ', err);
    // 处理不支持 clipboard API 的情况
    fallbackCopyTextToClipboard(url);
  }
};

const fallbackCopyTextToClipboard = text => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';  // 防止滚动时出现
  textArea.style.left = '-9999px';
  textArea.style.top = '-9999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    document.execCommand('copy');
    ElMessage.success("复制url链接成功！");
  } catch (err) {
    console.error('无法复制到剪贴板: ', err);
    ElMessage.error("复制url链接失败！");
  }
  document.body.removeChild(textArea);
};
onMounted(() => {
  search();
});
</script>

<style scoped lang="scss">
.iconHover:hover {
  background-color: var(--bee-hover-bg-color);
}

.isactive {
  background-color: var(--bee-active-bg-color); // 选中状态的背景颜色
  pointer-events: none; // 禁用悬停效果
}

.isactiveDeletedHover:hover {
  background-color: var(--el-color-primary-light-3);
}

.isactiveDeleted {
  background-color: var(--el-color-primary-light-3); // 选中状态的背景颜色
}
</style>
